package com.fwmagic.flink.window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

public class StreamCountWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        DataStreamSource<String> dataSource = env.socketTextStream("localhost", 8888);

        /** keyBy-> countWindow :分组统计各组内达到count次数的数据
         *  keyBy-> countWindowAll：分组统计同一个组内达到count次数的数据(对于单词统计而言，数据不一定准确的，因为单词hash到同一组即任务是一样的数据(单词))
         *
         * spark,1
         * hadoop,2
         * flink,1
         */
        SingleOutputStreamOperator<Tuple2<String, Integer>> maped = dataSource.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] arr = value.split(",");
                return Tuple2.of(arr[0], Integer.parseInt(arr[1]));
            }
        });

        WindowedStream<Tuple2<String, Integer>, Tuple, GlobalWindow> windowed = maped.keyBy(0).countWindow(5);
//        AllWindowedStream<Tuple2<String, Integer>, GlobalWindow> windowed = maped.keyBy(0).countWindowAll(5);

        SingleOutputStreamOperator<Tuple2<String, Integer>> sumed = windowed.sum(1);

        sumed.print();

        env.execute("StreamCountWindowAll");
    }
}
